import { treeAddress } from '@/services/api/api-pressconference';
import { ContactsOutlined, TeamOutlined, UserOutlined } from '@ant-design/icons';
import { DrawerForm } from '@ant-design/pro-form';
import { useAccess } from '@umijs/max';
import { Button, Space, Spin, Tag, Typography } from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import { useState } from 'react';
import EditAddress from './EditAddress';

interface TreeAddressProps {
  onSave: () => void;
}

const TreeAddress: React.FC<TreeAddressProps> = ({ onSave }) => {
  const [loading, setLoading] = useState(false);

  const [dataTreeAddress, setDataTreeAddressState] = useState<DataNode[]>();
  const access = useAccess();
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeAddressData(data: Array<UserData.Organization>): any {
    const treeData = new Array();
    console.log(data);

    if (data) {
      data.forEach((val: any, idx, array) => {
        if (val.isAddress === 1) {
          treeData.push({
            title: (
              <>
                <EditAddress
                  id={val.id}
                  name={val.name}
                  onSave={() => {
                    loadAddressTreeData();
                  }}
                />
                {val?.marks && val?.marks.length > 0 && (
                  <>
                    <Space wrap>
                      {val?.marks.map((item) => (
                        <Tag bordered={false} color="orange">
                          {item}
                        </Tag>
                      ))}
                    </Space>
                  </>
                )}
              </>
            ),
            key: val.id,
            icon: <ContactsOutlined />,
            children: readyTreeAddressData(val.children as Array<UserData.Organization>),
          });
        }

        if (val.isOrganization === 1) {
          treeData.push({
            title: (
              <>
                <span>{val.name}</span>
                {val?.marks && val?.marks.length > 0 && (
                  <>
                    
                    <Space wrap>
                      {val?.marks.map((item) => (
                        <Tag bordered={false} color="orange">
                          {item}
                        </Tag>
                      ))}
                    </Space>
                  </>
                )}
              </>
            ),
            key: val.id,
            // icon: val.isOrganizationType == 1 ? <BankOutlined />:<HomeOutlined />,
            children: readyTreeAddressData(val.children as Array<UserData.Organization>),
          });
        }

        if (val.isContact === 1) {
          treeData.push({
            title: (
              <>
                <span>{val.name}</span>
                {val?.marks && val?.marks.length > 0 && (
                  <>
                    
                    <Space wrap>
                      {val?.marks.map((item) => (
                        <Tag bordered={false} color="orange">
                          {item}
                        </Tag>
                      ))}
                    </Space>
                  </>
                )}
              </>
            ),
            key: val.id,
            icon: <UserOutlined />,
          });
        }
      });
    }
    console.log(treeData);

    return treeData;
  }
  /**
   * 加载组织树请求网络
   */
  const loadAddressTreeData = async () => {
    try {
      setLoading(true);
      const response = await treeAddress();

      if (response.code === 0) {
        setDataTreeAddressState(readyTreeAddressData(response.data));
      }

      setLoading(false);
    } catch (error) {}
  };
  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
  };
  return (
    <DrawerForm
      title="联络人"
      key={''}
      trigger={
        <Button key="button" icon={<TeamOutlined />}>
          联络人
        </Button>
      }
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        forceRender: true,
        destroyOnClose: true,
        width: 1000,
      }}
      submitter={false}
      onFinish={async (values) => {}}
      onValuesChange={(changedValues: any, allValues: any) => {}}
      onOpenChange={(visible) => {
        if (visible) {
          loadAddressTreeData();
        } else {
          setExpandedKeys([]);
        }
      }}
    >
      {!access.宣传指令x配置x通讯录修改专员 && (
        <EditAddress
          id={undefined}
          name={''}
          onSave={() => {
            loadAddressTreeData();
          }}
        />
      )}
      <div
        style={{
          marginTop: 10,
        }}
      >
        <Typography.Paragraph>
          <blockquote>点击根目录，可编辑该联络人列表</blockquote>
        </Typography.Paragraph>
        <Spin spinning={loading}>
          {dataTreeAddress && dataTreeAddress.length ? (
            <Tree
              treeData={dataTreeAddress}
              showIcon
              showLine
              selectable={false}
              onExpand={onExpand}
              expandedKeys={expandedKeys}
            />
          ) : (
            '暂无数据'
          )}
        </Spin>
      </div>
    </DrawerForm>
  );
};

export default TreeAddress;
